package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.constant.CoefficentCacheConstant;
import com.itheima.sfbx.insurance.constant.ConditionCacheConstant;
import com.itheima.sfbx.insurance.dto.CoefficentVO;
import com.itheima.sfbx.insurance.enums.CoefficentEnum;
import com.itheima.sfbx.insurance.mapper.CoefficentMapper;
import com.itheima.sfbx.insurance.pojo.CategoryCoefficent;
import com.itheima.sfbx.insurance.pojo.Coefficent;
import com.itheima.sfbx.insurance.pojo.InsuranceCoefficent;
import com.itheima.sfbx.insurance.service.ICategoryCoefficentService;
import com.itheima.sfbx.insurance.service.ICoefficentService;
import com.itheima.sfbx.insurance.service.IInsuranceCoefficentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description：系数项服务实现类
 */
@Slf4j
@Service
public class CoefficentServiceImpl extends ServiceImpl<CoefficentMapper, Coefficent> implements ICoefficentService {

    @Resource
    ICategoryCoefficentService categoryCoefficentService;
    @Resource
    IInsuranceCoefficentService insuranceCoefficentService;


    private LambdaQueryWrapper<Coefficent> queryWrapper(CoefficentVO coefficentVO){
        LambdaQueryWrapper<Coefficent> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StrUtil.isNotBlank(coefficentVO.getDataState()), Coefficent::getDataState, coefficentVO.getDataState())
                .like(StrUtil.isNotBlank(coefficentVO.getCoefficentKeyName()), Coefficent::getCoefficentKeyName, coefficentVO.getCoefficentKeyName())
                .eq(StrUtil.isNotBlank(coefficentVO.getCoefficentKey()), Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey());
        return lqw;
    }

    @Override
    @Transactional
    @Cacheable(value = CoefficentCacheConstant.PAGE,key = "#pageNum+'-'+#pageSize+'-'+#coefficentVO.hashCode()")
    public Page<CoefficentVO> findPage(CoefficentVO coefficentVO, int pageNum, int pageSize) {
        Page<Coefficent> page = this.page(new Page<>(pageNum, pageSize), queryWrapper(coefficentVO));
        return BeanConv.toPage(page, CoefficentVO.class);
    }

    @Override

    public CoefficentVO findById(String coefficentId) {
        //TODO
        return null;
    }

    @Override
    @Transactional
    @Caching(put = @CachePut(value = CoefficentCacheConstant.BASIC,key = "#coefficent.id"),
            evict = {
                    @CacheEvict(value = CoefficentCacheConstant.PAGE,allEntries = true),
                    @CacheEvict(value = CoefficentCacheConstant.LIST,allEntries = true)})
    public CoefficentVO save(CoefficentVO coefficentVO) {
        Integer count = this.lambdaQuery()
                .eq(Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .eq(Coefficent::getDataState, SuperConstant.DATA_STATE_0)
                .count();
        if (count>0){
            log.info("系数项已存在,保存失败：{}",coefficentVO.getCoefficentKey());
            throw new ProjectException(CoefficentEnum.SAVE_FAIL);
        }
        Coefficent bean = BeanConv.toBean(coefficentVO, Coefficent.class);
        save(bean);
        return BeanConv.toBean(bean, CoefficentVO.class);
    }

    @Override
    @Transactional
    @Caching(evict = {@CacheEvict(value = CoefficentCacheConstant.BASIC,key = "#coefficent.id"),
            @CacheEvict(value = CoefficentCacheConstant.PAGE,allEntries = true),
            @CacheEvict(value = CoefficentCacheConstant.LIST,allEntries = true)})
    public Boolean update(CoefficentVO coefficentVO) {
        //判断保障项是否存在
        Coefficent bean = this.getById(coefficentVO.getId());
        if (bean==null){
            log.error("系数项不存在,更新失败：{}",coefficentVO.getId());
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }

        Integer count = this.lambdaQuery()
                .eq(Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .ne(Coefficent::getId, coefficentVO.getCoefficentKey())
                .count();
        if (count>0){
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }
        //判断冗余字段，查关系，有关系不能修改
        Integer count1 = categoryCoefficentService.lambdaQuery()
                .eq(CategoryCoefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .count();
        Integer count2 = insuranceCoefficentService.lambdaQuery()
                .eq(InsuranceCoefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .count();
        if (count1>0 || count2>0){
            log.error("系数项不存在,有关联关系：{}",coefficentVO.getCoefficentKey());
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }

        return updateById(BeanConv.toBean(coefficentVO, Coefficent.class));
    }

    @Override
    @Transactional
    @Caching(evict = {@CacheEvict(value = CoefficentCacheConstant.BASIC,allEntries = true),
            @CacheEvict(value = CoefficentCacheConstant.PAGE,allEntries = true),
            @CacheEvict(value = CoefficentCacheConstant.LIST,allEntries = true)})
    public Boolean delete(String[] checkedIds) {
        List<String> ids = Arrays.asList(checkedIds);
        List<Coefficent> olds = this.listByIds(ids);
        if (CollUtil.isEmpty(olds)) {
            return true;
        }
        Set<String> keySet = olds.stream()
                .map(Coefficent::getCoefficentKey)
                .collect(Collectors.toSet());
        Integer count1 = categoryCoefficentService.lambdaQuery()
                .in(CategoryCoefficent::getCoefficentKey, keySet)
                .eq(CategoryCoefficent::getDataState,"0")
                .count();
        Integer count2 = insuranceCoefficentService.lambdaQuery()
                .in(InsuranceCoefficent::getCoefficentKey, keySet)
                .eq(InsuranceCoefficent::getDataState,"0")
                .count();
        if(count1>0||count2>0){
            log.error("已被方案或分类关联，无法删除：{}",keySet);
            throw new ProjectException(CoefficentEnum.DEL_FAIL);
        }
        return removeByIds(ids);
    }

    @Override
    @Cacheable(value = ConditionCacheConstant.LIST,key = "#coefficentVO.hashCode()")
    @Transactional
    public List<CoefficentVO> findList(CoefficentVO coefficentVO) {
        LambdaQueryWrapper<Coefficent> lqw = queryWrapper(coefficentVO);
        List<Coefficent> list = this.list(lqw);
        return BeanConv.toBeanList(list, CoefficentVO.class);
    }

    @Override
    @Cacheable(value = CoefficentCacheConstant.BASIC,key = "#result.id")
    @Transactional
    public CoefficentVO findByCoefficentKey(String coefficentKey) {
        Coefficent one = lambdaQuery()
                .eq(Coefficent::getCoefficentKey, coefficentKey)
                .eq(Coefficent::getDataState, SuperConstant.DATA_STATE_0)
                .one();
        return BeanConv.toBean(one, CoefficentVO.class);
    }
}
